const {
	userManageList,
	getUserManagerType
} = require('jvss/pagesDevice/device/device-live/door-lock/userManage/userManage.js');
import deviceLogin from '@/utils/deviceLogin.js';
const {
	convertdBm2RSSI,
	formatDate,
	compareVersions,
	calculateTimeDifference,
	desensitizeWifiName,
	getStatus,
	AlarmMsgIcon,
	showCloud,
	getBeforeDay,
	deviceStorage,
	turnTenToSixteen
} = require('@/utils/util.js');
let constant = getApp().globalData.constant;
let EE_DEV_SMARTDOORLOCK3 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK3;
let EE_DEV_SMARTDOORLOCK4 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK4;
let EE_DEV_SMARTDOORLOCK7 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK7;
const {
	msgInfoPrs
} = require('@/utils/msgInfoPrs.js');
export const lockHomeMixins = {
	data() {
		return {
			emptyFlag: 0,
			openInfo: [],
			replay: 'https://statics.xmcsrv.net/weixin/replay.png',
			deepSleep: 'https://statics.xmcsrv.net/weixin/live/deepSleep.png',
			sleeping: 'https://statics.xmcsrv.net/weixin/live/sleeping.png',
			offLine: 'https://statics.xmcsrv.net/weixin/live/offLine.png',

			// pviewUrl: 'https://statics.xmcsrv.net/weixin/defaultMsgBg2.png',
			pviewUrl: 'https://statics.xmcsrv.net/weixin/preview.png',
			pviewUrl1: 'https://statics.xmcsrv.net/weixin/previewBg1.png',

			playUrl: 'https://statics.xmcsrv.net/weixin/play.png',
			temporaryUrl: 'https://statics.xmcsrv.net/weixin/temporary.png',
			unlockUrl: 'https://statics.xmcsrv.net/weixin/unlocking.png',
			noMessageUrl: "https://statics.xmcsrv.net/weixin/noMessage.png",

			mode: 'default',
			swiperDotIndex: 0,
			isSwiper: null,
			infoHight: 300,
			infoScrollHight: 100,
			wifiUrl: 'https://statics.xmcsrv.net/weixin/wifi/wifiTwoError.png',
			isManualUnlocking: false,
			isTemporary: false,
			bl: 0,
			wifiName: '',

			tryCount: 0,
			tryTokenCount: 0,
			tryTimeOutCount: 0,

			msgType: '全部信息',
			list: [],
			sourceList: [],
			startTime: '',
			endTime: '',
			type: 1,
			jsonAlarmMsg: {},
			editInfo: {},
			lockStatus: null,
			count: '60',
			timer: null,
			isCountDown: false,

			PieStyle: {
				circular: '50rpx', // 当前圆的大小
				animite: false, // 是否要有动画效果
				ring: 0, // 中间是空心的宽度，0是不显示，0.5是半圆大小
				color: '#333', // 自定义饼图的颜色,
				numberShow: true, // 是否要显示圆中间的文本
				numberSize: '28rpx', // 中间文字大小默认是12px
				numberColor: '#fff', // 中间文字字体颜色
				rotate: 0, // 是否需要旋转图形
			},
			number_value: 0,

			isNonSpeaker: false, //true"无扬声器"
			isDevSpeaker: false,
			isbatteryPower: false, //电量

			total: 1,
			page: 1,
			pageSize: 15,
			triggered: true,

			sheetList: [],
			// previewPic:'https://statics.xmcsrv.net/weixin/preview.png',//预览退出后截一张图，如果第一条消息图片比这张图时间早，就用退出预览的图，否则显示第一张消息报警图，或者显示默认图片
			previewPic: "",
			isScrolltolower: false,
			AlarmTime: null,
			imgLoaded: false,
			defaultpreviewPic: "https://statics.xmcsrv.net/weixin/preview.png",
			isSupportUserManager: false, //是否支持用户管理
			userTypeMsk: '',
			currentIndex: 0,
			tabArr: ['通知消息', '用户管理'],
			userTypeList: [],
			showModal: false,
			isShowMsgLink:false, //是否显示消息联动入口

			startDialog: false,
			start2countDown: 30,
			startTimer: null,
			appletIdentify:getApp().globalData.appletIdentify,
			generalIdentify:getApp().globalData.generalIdentify,
			abnormalModal:false,//外网不通弹窗
			isContactFamily:false,//是否显示联系家人来电
			statusDescJson:{
				'deep':'设备已经处于深度休眠，无法远程唤醒',
				'OffLine':'设备可能不在线，请稍后重试',
				'sleeping':'让我先休眠一下，请稍后重试'
			},
			powerSavingMode:{},//省电模式
		}
	},
	watch: {
		device(val) {
			if (val.xmcCssVid || val.xmcVoes || val.pmsVoes || val.pmsSms || val.netCellular) {
				this.lockStatus = getStatus(this.device.status); // 设备状态
			}
		}
	},
	destroyed() {
		clearInterval(this.timer)
	},
	methods: {
		cancelAbnormal() {
			this.abnormalModal = false
		},
		onJumpToHelp() {
			uni.navigateTo({
				url: '/jvss/pagesMine/help/help'
			});
			this.cancelAbnormal()
		},
		//切换用户管理和通知消息
		onTabClickItem(e) {
			console.log('切换tab', e);
			this.currentIndex = e.currentIndex
		},
		getLoginSetting(callback) {
			uni.showLoading({
				mask: true,
			});
			let token = this.device.token;
			let data = {
				encryptType: 'DISABLE',
				LoginType: 'DVRIP-Web',
				UserName: 'admin',
				PassWord: this.device.devPassWord,
				Name: 'generalinfo'
			};
			if (this.device.adminToken) {
				data.LoginToken = this.device.adminToken
				data.encryptType = 'TOKEN'
			}
			getApp().globalData.api.deviceLogin(data, token, (result) => {
				uni.hideLoading();
				if (result.data.code === 2000) {
					// 登录成功 或 已登录
					if (result.data.data.Ret === 100 || result.data.data.Ret === 104) {
						console.log('成功')
						callback(result)
					} // 出错
					else {
						uni.showToast({
							icon: 'none',
							title: getApp().globalData.errCodeMsg.RetCodeMsg[result.data.data
								.Ret] || result.data.data.RetMsg,
						});
					}
				} else {
					uni.showToast({
						icon: 'none',
						title: getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result
							.data.msg
					});
				}
			})
		},
		// 低功耗设备唤醒
		wakeup(callback, decode = false, simple = false) {
			uni.showLoading({
				mask: true,
			});
			let data = {
				sn: this.device.deviceNo,
				hostedControl: "1", //是否唤醒主控（空值或0：不唤醒主控；1：唤醒主控）
			}
			getApp().globalData.api.wakeup(data, this.device.token, (result) => {
				uni.hideLoading()
				callback(result);
			}, decode, simple);
		},
		getWakeup(item) {
			this.wakeup((res) => {
				console.log(res, '唤醒主控')
				if (res.data.code == 2000) {
					this.getLoginSetting((res) => {
						this.checkWakeUp(item)
					})
				}
			})
		},
		//点击指纹、卡、密码等
		gridChange(item) {
			if (this.lockStatus == 'deep' || this.lockStatus == 'OffLine' || this.lockStatus == 'sleeping') {
				this.showModal = true
				return
			}
			let pages = getCurrentPages();
			let currentPage = pages[pages.length - 1];
			let url = currentPage.route
			uni.setStorageSync('startErrToPath', url)
			this.getWakeup(item)
		},
		// 检测锁板唤醒状态
		checkWakeUp(item) {
			this.getDoorLockTransparent(item, 'Start')
		},
		// 唤醒锁板
		wakeUpStart2(item) {
			this.getDoorLockTransparent(item, 'Start2')
		},
		getDoorLockTransparent(item, status) {
			if (status != 'Start2') {
				uni.showLoading({
					mask: true
				})
			}
			let data = {
				Name: 'OPDoorLockProCmd',
				OPDoorLockProCmd: {
					Cmd: "SyncDoorStatus",
					DoorStatus: {
						Status: status
					},
					SessionID: 0x00000001
				}
			};
			let token = this.device.token;
			getApp().globalData.api.doorLockTransparent(data, token, (result) => {
				console.log('检测是否需要唤醒锁板', result);
				uni.hideLoading()
				if (result.data.code == 2000) {
					let Err = turnTenToSixteen(result.data.data.DoorStatus.Err)
					if (result.data.data.DoorStatus.Err == 0) {
						if (status === 'Start') {
							// 指令发送成功后，改变缓存中start的状态为true
							uni.setStorage({
								key: 'StartFlag',
								data: {
									deviceNo: this.device.deviceNo,
									token: this.device.token,
									start: true
								},
								success: () => {
									console.log('Start指令发送成功')
									console.log(uni.getStorageSync('StartFlag'))
								}
							})
						}
					}
					if (status === 'Start2') {
						this.clearstart2Timer();
					}
					this.switchErr(Err, item, result)
				} else {
					uni.showToast({
						title: getApp().globalData.errCodeMsg.CodeMsg[result.data.code] || result
							.data.msg,
						icon: 'none',
						duration: 2000
					});
					this.clearstart2Timer();
				}
			}, false);
		},
		// 根据Err判断
		switchErr(Err, item, result) {
			switch (Err) {
				// 成功，跳转到具体设置页面
				case '0x00':
				case '0x12':
					this.jumpToSetting(item)
					break;
					// 需要唤醒，提示先唤醒锁板发Start2
				case '0x01':
					this.startDialog = true;
					// this.countDown()
					this.wakeUpStart2(item)
					break;
					// 	需要跳到管理员页面
				case '0x11':
					this.jumpToVerify(item)
					break;
				default:
					uni.showToast({
						title: getApp().globalData.errCodeMsg.wakeUpLockBoardCodeMsg[Err] || result.data
							.msg,
						icon: 'none',
						duration: 2000
					});
			}
		},
		// 检测唤醒锁板倒计时
		countDown() {
			this.startTimer = setInterval(() => {
				this.start2countDown--;
				if (this.start2countDown == 0) {
					this.clearstart2Timer()
				}
			}, 1000)
		},
		// 处理关闭倒计时
		clearstart2Timer() {
			console.log('关闭弹窗')
			this.startDialog = false;
			// clearInterval(this.startTimer)
			// this.startTimer = null;
			// this.start2countDown = 30;
		},
		// 跳转到验证页面
		jumpToVerify(item) {
			uni.navigateTo({
				// url:`${item.url}?userInfo=${JSON.stringify(item)}&device=${encodeURIComponent(JSON.stringify(this.device))}`
				url: `/jvss/pagesDevice/device/device-live/door-lock/userManage/verifyPassword?type=1&userInfo=${JSON.stringify(item)}&device=${encodeURIComponent(JSON.stringify(this.device))}`
			})
		},
		// 成功后直接跳转到设置页面
		jumpToSetting(item) {
			let userUrl =
				`/jvss/pagesDevice/device/device-live/door-lock/userManage/userList?userInfo=${JSON.stringify(item)}&device=${encodeURIComponent(JSON.stringify(this.device))}`
			uni.navigateTo({
				url: userUrl
			})
		},
		// 显示操作按钮
		shortcut() {
			if (uni.getStorageSync('manualUnlocking') == '0') {
				this.isManualUnlocking = false;
			} else {
				this.isManualUnlocking = true;
			}
			this.$nextTick(() => {
				this.getClineHeight();
			})
		},
		getReqCaps() {
			const data = {
				sn: this.device.deviceNo,
				caps: ['xmc.css', 'xmc.voes', 'pms.voes', 'pms.sms', 'net.cellular']
			};

			getApp().globalData.api.reqCaps(data, (result) => {
				// console.log('获取设备云服务信息',data)
				let caps = result.caps;
				let time = Math.floor(new Date().getTime() / 1000);
				const setServiceProperties = (serviceName, serviceNameType) => {
					const service = {
						support: caps[`${serviceNameType}.support`],
						enable: caps[`${serviceNameType}.enable`],
						expirate: caps[`${serviceNameType}.expirationtime`],
						isExpire: caps[`${serviceNameType}.expirationtime`] < time ? false : true
					};
					this.$set(this.device, serviceName, service);
				};
				setServiceProperties('xmcCssVid', 'xmc.css.vid'); // xmc.css.vid 云存储
				setServiceProperties('xmcVoes', 'xmc.voes'); // xmc.voes 云电话
				setServiceProperties('pmsVoes', 'pms.voes'); // pms.voes 语音报警
				setServiceProperties('pmsSms', 'pms.sms'); // pms.sms 短信报警
				setServiceProperties('netCellular', 'net.cellular'); // net.cellular 4G流量
				this.getXmc()
				// this.showCloud(this.device)
				this.sheetList = showCloud(this.device); // 云服务图标显示
				console.log(this.sheetList,'sheetList')
			})
		},
		// 判断是否有云服务和云电话
		getXmc() {
			// support true 支持 false 不支持
			// expirate 0 过期 
			// enable  false 未开通 true 开通
			let xmcCssVid = this.device.xmcCssVid;
			let xmcVoes = this.device.xmcVoes;
			console.log(this.device, xmcCssVid, xmcVoes)
			let time = Math.floor(new Date().getTime() / 1000);
			let url = '';
			this.openInfo = []
			if (xmcCssVid) {
				// 支持 
				if (xmcCssVid.support) {
					//       未开通                  过期
					if (!xmcCssVid.enable || xmcCssVid.expirate < time) {
						//   云存储
						this.openInfo.push({
							colorClass: 'uni-bg-blue',
							classifyId: "xmc.css",
							url: !xmcCssVid.enable ? 'https://statics.xmcsrv.net/weixin/openCloud.png' :
								'https://statics.xmcsrv.net/weixin/cloudExpiration.png',
							path: "/jvss/pageCloud/buy/default"
						}, )
					}
				}
			}
			if (xmcVoes) {
				if (xmcCssVid.support) {
					if (!xmcVoes.enable || xmcVoes.expirate < time) {
						// 云电话
						this.openInfo.push({
							colorClass: 'uni-bg-blue',
							classifyId: "xmc.voes",
							url: !xmcVoes.enable ? 'https://statics.xmcsrv.net/weixin/openCall.png' :
								"https://statics.xmcsrv.net/weixin/callExpired.png",
							path: '/jvss/pageCloud/buy/default'
						}, )
					}
				}
			}
			this.getaccountInfo();
		},
		// 判断是否显示轮播图
		getaccountInfo() {
			let version = getApp().globalData.version; // 1.0.0 小程序版本号
			let isversion = uni.getStorageSync('isversion' + this.device.deviceNo);
			let swiperInfo = uni.getStorageSync('isSwiper' + this.device.deviceNo)
			let isSwiper = swiperInfo && swiperInfo.deviceNo === this.device.deviceNo ? swiperInfo.status : null;
			if (this.openInfo.length > 0) {
				if (!isversion) { // 没有版本缓存
					uni.setStorageSync('isversion' + this.device.deviceNo, version);
					this.isSwiper = 'show';
				} else {
					const result = compareVersions(version, isversion);
					if (result == 1) {
						this.isSwiper = 'show';
						uni.setStorageSync('isSwiper' + this.device.deviceNo, {
							deviceNo: this.device.deviceNo,
							status: 'show'
						});
						uni.setStorageSync('isversion' + this.device.deviceNo, version);
					} else {
						this.isSwiper = isSwiper === 'none' ? 'none' : 'show';
					}
				}
				this.getClineHeight();
			}
		},
		// 关闭轮播图
		closeSwiper() {
			this.isSwiper = 'none';
			this.getClineHeight();
			uni.setStorageSync('isSwiper' + this.device.deviceNo, {
				deviceNo: this.device.deviceNo,
				status: 'none'
			})
		},
		// 轮播图事件
		swiperChange(e) {
			this.swiperDotIndex = e.detail.current
		},
		//获取可视区域高度
		getClineHeight() {
			setTimeout(() => {
				uni.getSystemInfo({
					success: (res => {
						const query = uni.createSelectorQuery().in(this);
						query.select('.lockInfo').boundingClientRect(data => {
							if (data) {
								this.infoHight = res.windowHeight - data.top -( this.isTab?8:15);
								this.infoScrollHight = this.infoHight - 69 //>更多40  button更多90
							}
						}).exec(resu => {});
					})
				});
			})
		},
		// 获取设备属性列表
		getDeviceTypePropListByPageForApp() {
			let data = {
				pid: this.device.pid,
				page: 1,
				limit: 999
			};
			getApp().globalData.api.getDeviceTypePropListByPageForApp(data, (result) => {
				let arr = []
				result.data.forEach(item => {
					if (item.propCode == "nonSpeaker") {
						this.isNonSpeaker = true
					}
					if (item.propCode == 'devSpeaker') {
						this.isDevSpeaker = true
					}
					if (item.propCode == "fullDuplex") {
						this.isFullDuplex = true
					}
					if (item.propCode == 'halfDuplex') {
						this.isHalfDuplex = true
					}
					if (item.propCode == 'wifiSignal') {
						arr.push('wifiSignal')
					}
					if (item.propCode == 'batteryPower') {
						arr.push('batteryPower')
					}
					if (item.propCode == "wifiName") {
						this.wifiName = desensitizeWifiName(item.propValue)
					}
					if (item.propCode == "tempPwd") {
						this.isTemporary = true
					}
					if(item.propCode == 'supportVideoCall' || item.propCode == 'supportAudioCall'){
						this.isContactFamily = true
					}
					if(item.propCode == "powerSavingMode"){
						this.powerSavingMode = item
						deviceStorage(this.device.deviceNo, 'powerSavingMode', item)
					}
				})
				
				if (arr.length > 0) {
					setTimeout(() => {
						this.getDevicePropStatus(arr)
					}, 100)
				}
			})
		},
		// 获取设备属性信息
		getDevicePropStatus(e) {
			let data = {
				"sn": this.device.deviceNo,
				"props": [...e, 'wifiName']
			};
			getApp().globalData.api.getDevicePropStatus(data, (result) => {
				if (result.wifiSignal) {
					this.wifiUrl = convertdBm2RSSI(result.wifiSignal, 2)
					deviceStorage(this.device.deviceNo, 'wifiSignal', this.wifiUrl)
				}
				this.wifiName = result.wifiName ? desensitizeWifiName(result.wifiName) : ''
				this.bl = result.batteryPower ? result.batteryPower : 0
				this.isbatteryPower = result.batteryPower ? true : false
				this.$logs({
					info: '获取WiFi信号和电量',
					data: data,
					result: result,
				}, 'error')
			});
		},
		// 获取影子服务离线配置
		getTailoredConfig(callback) {
			let token = this.device.token
			let data = {
				"sn": this.device.deviceNo,
				"configs": []
			};
			getApp().globalData.api.getTailoredConfig(data, token, (result) => {
				// this.wifiUrl = convertdBm2RSSI(result.wsl, 2)
				if (result.dlctrl) {
					if (result.dlctrl.DlUser && Object.keys(result.dlctrl.DlUser).length > 0) {
						this.isSupportUserManager = true
						this.userTypeMsk = getUserManagerType(result.dlctrl.DlUser.TypeMsk);
						let list = userManageList()
						let userList = this.userTypeMsk.split('')
						this.userTypeList = list.map((item, index) => {
							return {
								...item,
								show: userList[index] == 1
							}
						})
					}
				}
				if(typeof callback == 'function'){
					callback(result.DouCamStreamInfo&&result.DouCamStreamInfo.DouCamStat)
				}
			});
		},
		// mqtt信息
		getUiMqttInfoCallback(res) {
			let info = JSON.parse(res)
			// console.log(info, 'lockHome Mqtt信息', this.device)
			let device = this.device
			if (info.sn == device.deviceNo) {
				let status = ''
				info.props.forEach(item => {
					if (item.propCode == "wifiSignal") {
						this.wifiUrl = convertdBm2RSSI(item.propValue, 2)
						deviceStorage(device.deviceNo, 'wifiSignal', this.wifiUrl)
					}
					if (item.propCode == "batteryPower") {
						this.bl = item.propValue
					}
					if (item.propCode == "sleepState") {
						status = item.propValue
					}
					if (item.propCode == "wifiName") {
						this.wifiName = desensitizeWifiName(item.propValue)
						deviceStorage(device.deviceNo, 'wifiName', this.wifiName)
					}
				})
				switch (status) {
					case 'DeepSleep':
						this.lockStatus = 'deep';
						this.setDeviceStatus(device, '0', '0', 'online');
						break;
					case 'LightSleep':
						this.lockStatus = 'dormancy';
						this.setDeviceStatus(device, '1', '0', 'online');
						break;
					case 'PreSleep':
						this.lockStatus = 'sleeping';
						this.setDeviceStatus(device, '1', '2', 'online');
						break;
					case 'WakeUp':
					case 'MasterControlPreSleep':
						this.lockStatus = 'online';
						this.setDeviceStatus(device, '1', '1', 'online');
						break;
					case 'OffLine':
						// this.lockStatus = 'OffLine';
						// this.setDeviceStatus(device, '', '', 'notfound');
						setTimeout(() => {
							if (this.lockStatus == 'OffLine') {
								this.getDeviceStatus()
							}
						}, 3000)
						break;
				}
				this.$logs({
					info: '门锁接收到的状态',
					deviceNo: this.device.deviceNo,
					lockStatus: this.lockStatus,
				})
			}
		},
		// 设备状态
		setDeviceStatus(device, wakeUpEnable, wakeUpStatus, status) {
			if (device.status) {
				device.status.wakeUpEnable = wakeUpEnable;
				device.status.wakeUpStatus = wakeUpStatus;
				device.status.status = status;
			} else {
				let s = {
					wakeUpEnable,
					wakeUpStatus,
					status
				};
				this.$set(device, 'status', s);
			}
			this.device = device
		},
		// 获取设备状态
		getDeviceStatus(tokenList, deviceList, type) {
			const data = {
				otherStatus: true,
				token: [this.device.token]
			};
			getApp().globalData.api.getDeviceStatus(data, (result) => {
				this.device.status = result[0];
				this.lockStatus = getStatus(this.device.status); // 设备状态
			});
		},
		// 告警消息
		AlarmEventInfo(res) {
			let info = JSON.parse(res);
			if (info.SerialNumber == this.device.deviceNo) {
				this.getMsgName();
			}
		},
		//临时密码
		tempPwdClick() {
			uni.navigateTo({
				url: `/jvss/pagesDevice/device/device-live/door-lock/temporaryLx?device=${encodeURIComponent(JSON.stringify(this.device))}`
			})
		},
		// 联系家人
		contactFamily(){
			let content = this.statusDescJson[this.lockStatus]
			if(this.lockStatus == 'deep'){
				return this.showStatusToast(content)
			}else if(this.lockStatus == 'OffLine'){
				return this.showStatusToast(content)
			}else if(this.lockStatus == 'sleeping'){
				return this.showStatusToast(content)
			}
			this.getTailoredConfig((douCamStat)=>{
				if(douCamStat == 1){
					uni.navigateTo({
						url: '/jvss/pagesDevice/device/device-live/door-lock/live-familyCall?device=' + encodeURIComponent(JSON
						.stringify(this.device))
					})
				}else{
					uni.showModal({
						title:'提示',
						content:'需要启用门内摄像头后才可使用该功能,是否去启用？',
						success: (res) => {
							if(res.confirm){
								this.onSetting()
							}
						}
					})
				}
			})
		},
		// 开锁
		unlockClick() {
			let content = this.statusDescJson[this.lockStatus]
			if (this.lockStatus == 'deep') {
				return this.showStatusToast(content)
			}
			if (this.lockStatus == 'OffLine') {
				return this.showStatusToast(content)
			}
			if (this.lockStatus == 'sleeping') {
				return this.showStatusToast(content)
			}
			let LOCK3 = EE_DEV_SMARTDOORLOCK3; //博克 AHD
			let LOCK4 = EE_DEV_SMARTDOORLOCK4; // 博克乐鑫XM650主PID
			let LOCK7 = EE_DEV_SMARTDOORLOCK7; // 博克乐鑫主pid
			let LOCK11 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK11; // 博克乐鑫新UI主pid
			if ((this.device.parentPid == LOCK7 ||
					this.device.parentPid == LOCK3 ||
					this.device.parentPid == LOCK4 ||
					this.device.parentPid == LOCK11) &&
				this.appletIdentify != this.generalIdentify) {
				this.getUnlockClickMsgList();
				return;
			}
			this.$refs.inputDialog.open();
		},
		//显示吐司弹框
		showStatusToast(content){
			uni.showToast({
				title: content,
				icon: 'none',
				mask: true
			})
		},
		// 取消开锁
		cancel() {
			this.$refs.inputDialog.close()
		},
		//确认开锁
		confimeUnlock() {
			this.getLogin()
		},
		// 博客设备按门铃60s查询
		getUnlockClickMsgList() {
			let currentDate = new Date().toJSON().split('T')[0]
			let startTime = getBeforeDay(-6) + ' ' + '00:00:00'
			let endTime = getBeforeDay(0) + ' ' + '23:59:59'
			let token = this.device.token
			let data = {
				sn: this.device.deviceNo,
				startTime: startTime,
				endTime: endTime,
				AlarmEvent: '',
				pageSize: 10,
				pageNum: 1
			}
			getApp().globalData.api.getLockAlarmMSgList(data, token, (result) => {
				let list = result.AlarmArray || []
				let callList = []
				let remoteLockArr = []
				list.forEach((item) => {
					if (item.AlarmEvent.includes('DoorLockCall')) {
						callList.push(item)
					}
					if (this.isJSON(item.AlarmMsg)) {
						let AlarmMsg = JSON.parse(item.AlarmMsg)
						if (AlarmMsg.MsgType == 'Remote') {
							remoteLockArr.push(item)
						}
					}
				})
				if (callList.length > 0) {
					let currentTime = new Date().getTime()
					let msgTime = new Date(callList[0].AlarmTime.replaceAll('-', '/')).getTime()
					let lastUnlockTime = 0
					if (remoteLockArr.length > 0) {
						lastUnlockTime = new Date(remoteLockArr[0].AlarmTime.replaceAll('-', '/')).getTime()
					}
					if (Number(msgTime) + (60 * 1000) > currentTime) {
						if (Number(msgTime) < Number(lastUnlockTime)) {
							uni.showToast({
								title: '请按锁端门铃按键发起远程开锁请求',
								icon: 'none'
							})
						} else {
							this.$refs.inputDialog.open()
						}
					} else {
						uni.showToast({
							title: '请按锁端门铃按键发起远程开锁请求',
							icon: 'none'
						})
						this.$logs({
							info: '开锁1',
							msgTime: msgTime,
							currentTime: currentTime,
							lastUnlockTime: lastUnlockTime
						}, 'error')
					}
				} else {
					uni.showToast({
						title: '请按锁端门铃按键发起远程开锁请求',
						icon: 'none'
					})
					this.$logs({
						info: '开锁2',
						callList: callList,
						res: result
					}, 'error')
				}
			})
		},
		// 设备登录
		getLogin() {
			deviceLogin(this.device, (result) => {
				console.log(result, '登录接口')
				if (result.data.Ret === 100 || result.data.Ret === 104) {
					this.getUnlock()
				}
			})
		},
		// 开锁
		getUnlock() {
			uni.showLoading({
				title: '正在开锁'
			})
			let token = this.device.token;
			let data = {
				sn: this.device.deviceNo,
				props: {
					"doorLock": {
						"remoteOneKeyUnlock": 1
					}
				}
			};
			getApp().globalData.api.remoteUnlock(data, token, (result) => {
				uni.hideLoading();
				this.cancel()
				if (result.Ret === 100) {
					uni.showToast({
						title: '开锁成功',
					});
					setTimeout(() => {
						uni.$emit('deviceLogout', {
							isBack: true,
							deviceNo: this.device.deviceNo,
							token: this.device.token
						})
					}, 1000)
				} else {
					uni.showToast({
						title: '开锁失败',
						icon: 'error'
					});
				}
			});
		},
		// 轮播图跳转
		toPath(e) {
			uni.navigateTo({
				url: '/jvss/pageCloud/buy/default?classifyId=' + e.classifyId + '&sn=' + this.device
					.deviceNo
			})
		},
		onOk() {
			this.showModal = false
		},
		onCancel() {
			uni.navigateTo({
				url: '/jvss/pagesMine/help/help'
			})
		},
		// 跳转到播放页
		toLive() {
			this.$logs({
				info: '跳转到播放页门锁接的状态',
				deviceNo: this.device.deviceNo,
				lockStatus: this.lockStatus,
			})
			if (this.lockStatus == 'deep' || this.lockStatus == 'OffLine' || this.lockStatus == 'sleeping') {
				this.showModal = true
				return
			}
			let url = '/jvss/pagesDevice/device/device-live/door-lock/live-lexin2?device=' + encodeURIComponent(JSON
				.stringify(this.device));
			if (this.isCountDown) {
				let AlarmTime = this.sourceList[0].AlarmTime ? this.sourceList[0].AlarmTime : null
				url =
					`/jvss/pagesDevice/device/device-live/door-lock/live-lexin2?device=${encodeURIComponent(JSON.stringify(this.device))}&type=${'doorbell'}&AlarmTime=${AlarmTime}`
			}
			if(this.device.deviceNo == '406d741ad2e7f957' || this.device.deviceNo == 'f6d56ce7366d8bd7' || this.device.deviceNo == 'af9d5e5433cd0ae3'){
				url = '/jvss/pagesDevice/device/device-live/door-lock/live-familyCall?device=' + encodeURIComponent(JSON
				.stringify(this.device))
			}
			uni.navigateTo({
				url: url
			})
		},
		// 门铃来电跳转到预览页的时候需要挂断云电话
		voesCallHangup(callback) {
			let token = this.device.token
			let data = {
				userId: uni.getStorageSync('userInfo').userId,
				sn: this.device.deviceNo
			}
			getApp().globalData.api.voesCallHangup(data, token, (result) => {
				if (typeof callback == 'function') {
					callback(result)
				}
				this.$logs({
					info: '点击消息列表倒计时消息时候需要调用挂断云电话',
					data: data,
					result: result
				})
			});
		},
		// 跳转消息视频
		itemClick(item, index) {
			const videoInfo = item.VideoInfo ? item.VideoInfo : ''
			const i = Math.ceil(index / 10)
			let url = '/jvss/pagesDevice/device/device-live/door-lock/cloudMsg?queryAlarmId=' +
				item.AlarmId + '&device=' + encodeURIComponent(JSON.stringify(this.device)) + '&onTap=' + '1' +
				'&size=' + i + '&videoInfo=' + videoInfo
			if (index == 0 && this.isCountDown) {
				url =
					`/jvss/pagesDevice/device/device-live/door-lock/live-lexin2?device=${encodeURIComponent(JSON.stringify(this.device))}&type=${'doorbell'}&AlarmTime=${item.AlarmTime}&playOrNot=${'suspend'}`
				this.voesCallHangup()
			}
			uni.navigateTo({
				url: url
			})
		},
		// 查看更多消息
		toCloudMsg() {
			let url = '/jvss/pagesDevice/device/device-live/door-lock/cloudMsg?device=' + encodeURIComponent(
				JSON.stringify(this.device))
			uni.navigateTo({
				url: url
			})
		},
		//上拉加载分页
		scrolltolower() {
			this.page++;
			this.isScrolltolower = true; //上拉加载更多 首图不让加载
			this.getMsgList((this.filterTypeItem && this.filterTypeItem.value) || 'all')
		},
		onRefresh() {
			this.AlarmTime = this.sourceList.length ? this.sourceList[0].AlarmTime : null
			if (this.freshing) return
			this.freshing = true
			this.triggered = true
			this.page = 1
			if (!(this.type == 2 && this.deviceList.length == 0)) {
				this.getMsgList()
			}
			setTimeout(() => {
				this.triggered = false
				this.freshing = false
			}, 1000)
		},
		// 更多
		onPopup(ev) {
			this.$emit('onBindlongtapDevice',ev, 'ui_doorlock_home')
			// this.$parent.onBindlongtapDevice(ev, 'ui_doorlock_home')
			// this.$parent.onBindlongtapDevice(ev)
		},
		// 云服务弹窗
		showCloudStorge(ev) {
			this.$emit('showCloudStorge',ev)
			// this.$parent.showCloudStorge(ev)
		},
		// 跳转消息设置
		msgSetting() {
			uni.navigateTo({
				url: `/jvss/pagesDevice/device/device-live/door-lock/msgNotification?device=${encodeURIComponent(JSON.stringify(this.device))}`
			})
		},
		// 跳转设置
		onSetting() {
			this.saveLoginInfo();
			let url =
				`/jvss/pagesDevice/device/device-live/door-lock/setting/setting-lexin?device=${encodeURIComponent(JSON.stringify(this.device))}&type=${'tab'}&powerSavingMode=${encodeURIComponent(JSON.stringify(this.powerSavingMode))}`
			uni.navigateTo({
				url
			})
		},
		// 缓存设备信息
		saveLoginInfo() {
			let deviceList = uni.getStorageSync('deviceList') || [];
			let isCache = false
			deviceList.forEach((item) => {
				if (this.device.deviceNo == item.deviceNo) {
					isCache = true
				}
			})
			if (!isCache) {
				deviceList.push(this.device);
			}
			uni.setStorageSync('deviceList', deviceList);
		},
		//获取昵称
		getMsgName() {
			const data = {
				deviceSn: this.device.deviceNo
			};
			getApp().globalData.api.getLockAlarmMSgName(data, (result) => {
				this.editInfo = result
				this.getMsgList()
			});
		},
		//获取消息列表
		getMsgList() {
			let token = this.device.token
			let data = {
				sn: this.device.deviceNo,
				startTime: this.startTime,
				endTime: this.endTime,
				pageSize: this.pageSize,
				pageNum: this.page,
				protocolFmt: '0'
			}
			getApp().globalData.api.getLockAlarmMSgList(data, token, (result) => {
				uni.hideLoading()
				this.total = result.AlarmArray ? result.AlarmArray.length : 1
				if (this.page == 1) {
					this.sourceList = []
				}
				this.sourceList = this.sourceList.concat(result.AlarmArray)
				if (this.sourceList.length > 0) {
					this.sourceList.forEach((item, index) => {
						item.date = item.AlarmTime.split(' ')[0]
						item.AlarmEvent = item.AlarmEvent.split(':')[0]
						item = msgInfoPrs(item, this.jsonAlarmMsg, this.editInfo)
						if (item.PicInfo && item.PicInfo.ObjName) {}
						item.AlarmMsgIcon = AlarmMsgIcon(item)
					})
					if (this.sourceList.length > 0) {
						if (this.$refs.jPie) {
							this.$refs.jPie[0].div_2_style = ''
						}
						this.callCountDown()
					}
					let cacheData = uni.getStorageSync(this.device.deviceNo)
					let alarmTime = new Date(this.sourceList[0].AlarmTime.replace(/-/g, '/')).getTime()
					if (cacheData && cacheData.previewCapture) {
						if (alarmTime < cacheData.previewCapture.time) {
							this.previewPic = cacheData.previewCapture.url
						} else {
							if (!this.isScrolltolower) {
								this.showPicView()
							}
						}
					} else {
						if (!this.isScrolltolower) {
							this.showPicView()
						}
					}
					this.isScrolltolower = false;
				} else {
					if (!this.isScrolltolower) {
						this.previewPic = this.pviewUrl
					}
				}
				this.emptyFlag = 1;
			});
		},
		showPicView() {
			let obj = this.sourceList[0]
			if (this.AlarmTime) {
				if (obj.AlarmTime != this.AlarmTime) {
					this.previewPic = obj.PicInfo ? obj.PicInfo.Url : this.pviewUrl
					// this.previewPic = this.sourceList[0].alarmImageUrl ? this.sourceList[0].alarmImageUrl : ''
				}
			} else {
				this.previewPic = obj.PicInfo ? obj.PicInfo.Url : this.pviewUrl
				// this.previewPic = this.sourceList[0].alarmImageUrl ? this.sourceList[0].alarmImageUrl : ''
			}
		},
		callCountDown() {
			if (this.timer) this.clearTimer()
			let ev = this.sourceList[0];
			if (ev.AlarmEvent !== 'DoorLockCall') return;
			let difference = this.MyGetTimeS(formatDate(new Date()), ev.AlarmTime);
			if (difference > 60) return
			this.isCountDown = true
			const TIME_COUNT = calculateTimeDifference(ev.AlarmTime, 1);
			this.number_value = (60 - TIME_COUNT) * (1 / 60)
			if (!this.timer) {
				this.count = TIME_COUNT
				this.timer = setInterval(() => {
					if (this.count > 0 && this.count <= TIME_COUNT) {
						this.count--;
						this.number_value = this.number_value + (1 / 60);
					} else {
						this.clearTimer()
					}
				}, 1000)
			}
		},
		clearTimer() {
			this.isCountDown = false
			clearInterval(this.timer)
			this.timer = null;
			this.number_value = 0;
		},
		MyGetTimeS(inDStr1, inDStr2) {
			let D1 = this.DateInitFromStr(inDStr1);
			let D2 = this.DateInitFromStr(inDStr2);
			return ((D1.getTime() - D2.getTime()) / 1000);
		},
		DateInitFromStr(inStr) {
			return new Date(inStr.replace(/-/g, '/'))
		},
		isJSON(str) {
			if (typeof str == 'string') {
				try {
					var obj = JSON.parse(str);
					if (typeof obj == 'object' && obj) {
						return true;
					} else {
						return false;
					}
				} catch (e) {
					return false;
				}
			}
		},
		onSuccessImg(item) {
			this.imgLoaded = true
		},
		// 上报图片 错误处理
		imageError(e, index) {
			if (index == -1) {
				this.previewPic = this.pviewUrl
				this.imgLoaded = false
				// this.previewPic = ''
			} else {
				this.sourceList[index].PicInfo.Url = this.pviewUrl1 //this.pviewUrl1 ''
			}
		}
	}
}